class UserborrowController < ApplicationController
  before_filter :require_login
  def borrow
    user = session[:user]
    bookid = params[:bookid]
    borrow = Borrow.find(:all,:conditions => ["user_id = ? AND book_id = ?",user.id,bookid])
    if borrow.size > 0
      flash[:message] = "You borrowed this book"
      redirect_to :controller => 'bookDetail',:action =>'show',:id => bookid
    else
      book = Book.find(bookid) 
      borrow = Borrow.new
      borrow.user_id = user.id
      borrow.book_id = book.id
      borrow.borrowed_date = Date.today
      borrow.return_date = Date.today + 10
      borrow.deposit = book.price
      borrow.save
      book.current_quantity = book.current_quantity - 1
      book.numborrowed = book.numborrowed + 1
      book.save
      flash[:message] = "Congratulation you on borrow '"+ book.title+"' successfully, please come the library to receive the book"
      redirect_to root_url
      end
  end
end
